//
//  PhotosView.m
//  CMJWeibo
//
//  Created by BH on 16/1/4.
//
//

#import "PhotosView.h"
#import "PhotoView.h"
#import "Photo.h"
#import "UIView+MJ.h"
#import "CMJCommon.h"
#import <MJPhotoBrowser/MJPhoto.h>
#import <MJPhotoBrowser/MJPhotoBrowser.h>

@implementation PhotosView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //创建9张图片
        for (int i=0; i<9; i++) {
            PhotoView *photoV = [[PhotoView alloc] init];
            photoV.tag = i;
            [self addSubview:photoV];
            
            [photoV addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(photoViewTap:)]];
        }
    }
    return self;
}

/**
 *  图片点击事件
 */
-(void)photoViewTap:(UITapGestureRecognizer *)tap
{
    //创建浏览器对象
    MJPhotoBrowser *photoBrowser = [[MJPhotoBrowser alloc] init];
    
    //设置浏览器对象的所有图片
    NSMutableArray *photosArr = [NSMutableArray array];
    for (int i=0; i<self.photosArr.count; i++) {
        // 取出图片模型
        Photo *photo = self.photosArr[i];
        // 创建MJPhoto模型
        MJPhoto *mjPhoto = [[MJPhoto alloc] init];
        // 设置图片的url
        mjPhoto.url = [NSURL URLWithString:photo.bmiddle_pic];
        // 设置图片的来源view
        mjPhoto.srcImageView = self.subviews[i];
        
        [photosArr addObject:mjPhoto];
    }
    photoBrowser.photos = photosArr;
    
    //设置浏览器默认显示的图片位置
    photoBrowser.currentPhotoIndex = tap.view.tag;
    [photoBrowser show];
}

-(void)setPhotosArr:(NSArray *)photosArr
{
    _photosArr = photosArr;
    //是否显示图片
    NSInteger photosCount = photosArr.count;
    if (photosCount==0) {
        //没有图片时隐藏
        self.hidden = YES;
        return;
    }else{
        self.hidden = NO;
    }
    
    //给图片控件显示图片
    for (int i=0; i<9; i++) {
        PhotoView *photoV = self.subviews[i];
        
        if (i<photosCount) {
            photoV.hidden = NO;
            photoV.photo = photosArr[i];
        }else{
            photoV.hidden = YES;
        }
    }
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    for (int i=0; i<self.photosArr.count; i++) {
        // 取出子控件
        PhotoView *photoV = self.subviews[i];
        
        // 设置frame
        photoV.width = PhotoWidth;
        photoV.height = PhotoHeight;
        
        // 一行最多的列数
        NSInteger maxCols = (self.photosArr.count == 4)?2:3;
        
        NSInteger col = i % maxCols;
        photoV.x = col * (PhotoWidth + PhotoMargin);
        
        NSInteger row = i / maxCols;
        photoV.y = row * (PhotoHeight + PhotoMargin);
    }
}

@end
